package com.huntmobi.springsecuritydemo.base.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huntmobi.springsecuritydemo.base.dto.syslog.FormLoginDto;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @BelongsProject: spring-security-demo
 * @BelongPackage: com.huntmobi.springsecuritydemo.base.filter
 * @Author: zouzhimin
 * @Date: 2020/11/19 11:40
 * @Description: 自定义登录流程
 **/
@Setter
@Getter
public class JsonLoginFilter extends AbstractAuthenticationProcessingFilter {

    private ObjectMapper objectMapper;

    private UsernamePasswordAuthenticationToken authRequest = null;

    public JsonLoginFilter() {
        super(new AntPathRequestMatcher("/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        try(InputStream inputStream = httpServletRequest.getInputStream()) {
            FormLoginDto formLoginDto = new ObjectMapper().readValue(inputStream,FormLoginDto.class);
            authRequest =  new UsernamePasswordAuthenticationToken(formLoginDto.getUsername(),formLoginDto.getPassword());
        } catch (IOException e) {
            e.printStackTrace();
            authRequest = new UsernamePasswordAuthenticationToken("", "");
        }finally {
            return getAuthenticationManager().authenticate(authRequest);
        }

    }
}
